package com.example.websocket.excel.util;

import java.util.Random;

/**
 * 
 * 生成随机密码和用户名
 *
 */
public class RandomStringUtils {

	private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";
	
	private static int nextIndex(char[] chars, Random rnd) {
		int index = rnd.nextInt(chars.length);
		while (chars[index] != 0) {
			index = rnd.nextInt(chars.length);
		}
		return index;
	}
	
	private static char nextSpecialChar(Random rnd) {
		return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
	}
	
    private static char nextUpperlLetter(Random rnd) {
        return (char) ('A' + rnd.nextInt(26));
    }

    private static char nextLowerLetter(Random rnd) {
        return (char) ('a' + rnd.nextInt(26));
    }

    private static char nextNumLetter(Random rnd) {
        return (char) ('0' + rnd.nextInt(10));
    }
    
    private static char nextChar(Random rnd) {
    	switch (rnd.nextInt(4)) {
           case 0:
              return (char) ('a' + rnd.nextInt(26));
           case 1:
              return (char) ('A' + rnd.nextInt(26));
           case 2:
              return (char) ('0' + rnd.nextInt(10));
           default:
              return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
		}
    }
    
    public static String randomPassword(int num) {
    	char[] chars = new char[num];
    	Random rnd = new Random();
        chars[nextIndex(chars, rnd)] = nextSpecialChar(rnd);
        chars[nextIndex(chars, rnd)] = nextUpperlLetter(rnd);
        chars[nextIndex(chars, rnd)] = nextLowerLetter(rnd);
        chars[nextIndex(chars, rnd)] = nextNumLetter(rnd);
        for (int i = 0; i < num; i++) {
        	if (chars[i] == 0) {
        		chars[i] = nextChar(rnd);
        	}
        }
        return new String(chars);
    }
    
    public static String getStringRandom(int length) {
    	String val = "";
    	Random random = new Random();
    	for (int i = 0; i < length; i++) {
    		String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
    		if ("char".equalsIgnoreCase(charOrNum)) {
    			int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
    			val += (char)(random.nextInt(26) + temp);
    		} else if ("num".equalsIgnoreCase(charOrNum)) {
    			val += String.valueOf(random.nextInt(10));
    		}
    	}
    	return val;
    }
    
}
